package filters;

import helpers.LanguageHelper;
import helpers.SettingHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import user.models.UserModel;

import models.ApplicationConfigModel;
import models.ApplicationModel;

import admin.models.ApplicationMappingModel;

import com.google.appengine.api.NamespaceManager;

import debugs.ApplicationConfigDebug;
import debugs.ApplicationDebug;
import debugs.ApplicationMappingDebug;

import entities.Application;
import entities.ApplicationConfig;
import entities.ApplicationMapping;
import entities.User;

public final class UrlFilter implements Filter {
	
	private static final Logger log = Logger.getLogger(UrlFilter.class
			.getName());
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		
		String path = ((HttpServletRequest) request).getRequestURI();
		
		if (!path.contains("/admin/")) {
			//Check domain name
			String siteName = req.getServerName();
			//log.warning("---------------->" + siteName);
			if (!siteName.equals(SettingHelper.getDomain())) {
				if (siteName.contains(SettingHelper.getDomain())) {
					String subDomain = siteName.replace("." + SettingHelper.getDomain(),"");
					ApplicationModel appModel = ApplicationModel.getInstance();
					Application obj = appModel.get(subDomain);
					if (obj != null) {
						try {
							ApplicationConfigModel appConfigModel = ApplicationConfigModel.getInstance();
							ApplicationConfig appConfig = appConfigModel.get(obj.getId(), obj.getId());
							
							
							
							NamespaceManager.set(obj.getId());
							if (appConfig != null) {
								request.setAttribute("sysConfig", appConfig);
							} else {
								response.getWriter().print(
										"Please try again later !");
								log.warning("Config or template are null !");
							}
						} catch (Exception e) {
							response.getWriter().print("Please try again later !");
						}
						
					} else {
						NamespaceManager.set(SettingHelper.getGeneralNamespace());
					}
				} else {
					siteName = siteName.replace("http://", "").replace("www.", "");
					
					ApplicationMappingModel appMappingModel = ApplicationMappingModel.getInstance();
					ApplicationMapping appMapping = appMappingModel.get(siteName);
					
					if (appMapping != null) {
						ApplicationConfigModel appConfigModel = ApplicationConfigModel.getInstance();
						ApplicationConfig appConfig = appConfigModel.get(appMapping.getApplicationId(), appMapping.getApplicationId());
						
						if (appConfig != null) {
							NamespaceManager.set(appConfig.getApplicationId());
						}
							
						request.setAttribute("sysConfig", appConfig);
						
					} else {
						//response.getWriter().print("Invalid url !");
					}
					
				}
			} else {
				NamespaceManager.set(SettingHelper.getGeneralNamespace());
			}
		} else {
			NamespaceManager.set(SettingHelper.getGeneralNamespace());
		}
		
		//Check user login
		User user = null;
		LanguageHelper languageTranslate = new LanguageHelper(req);
		if (req.getUserPrincipal() != null) {
			UserModel userModel = UserModel.getInstance();
			user = userModel.getByUsername(NamespaceManager.get(), req.getUserPrincipal().getName());
		}
		request.setAttribute("user_logged_in", user);
		request.setAttribute("language", languageTranslate.getLanguage());
		
		chain.doFilter(request, response);
		return;
	}

	public void destroy() {

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
}